﻿using System;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;
using System.Text.RegularExpressions;

namespace Portal.CDSP
{
    public class FResultSearchWP : WebPart
    {
        public override string WebPartId
        {
            get
            {
                return "WebSite.FResultSearchWP";
            }
        }

        public override string WebPartFolder
        {
            get
            {
                return "Portal.CDSP";
            }
        }


        public override string Title
        {
            get
            {
                return GetText("Title", "CDSP-Kết quả tìm kiếm");
            }
        }

        public override ViewCls[] Views
        {
            get
            {
                return new ViewCls[]{
                    new ViewCls("default",GetText("default","Kết quả tìm kiếm"),1),
                };
            }
        }

        public override string NameSpace
        {
            get
            {
                return "Portal.CDSP";
            }
        }

        public override string ClassName
        {
            get
            {
                return "FResultSearchWP";
            }
        }


        private string ClientRenderWebPart(string TabModuleId, string HasPorlet)
        {
            try
            {
                string belongSite = string.Empty;
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));
                belongSite = TabModuleCls.belongSite;
                string Html = string.Empty;
                if (Environments.Request("sKeyword") == null && Environments.Request("sk") == null)
                {
                    Html =
                        "<div class=\"clrfix\"></div>" +
                        "<div class=cssNotFoundKeywordInfo>" + GetText("1657A8D5-3458-4a12-80CE-EB4AD7DA962C", "Chưa xác định từ khóa tìm kiếm") + "</div>";
                }
                else
                {
                    string Keyword = (string)Environments.Request("sKeyword");
                    if (Keyword == null) Keyword = "";
                    if (Keyword.Trim().Length == 0)
                    {
                        Keyword = (string)Environments.Request("sk");
                    }
                    if (Keyword == null) Keyword = "";
                    string ServiceId = "";
                    try
                    {
                        ServiceId = (string)Environments.Request("sServiceId");
                    }
                    catch { }
                    if (ServiceId == null) ServiceId = "";
                    string ShortGroupNewsItemId = "";
                    try
                    {
                        ShortGroupNewsItemId = (string)Environments.Request("sg");
                    }
                    catch { }
                    if (ShortGroupNewsItemId == null) ShortGroupNewsItemId = "";
                    if (Keyword.Trim().Length > 0)
                    {
                        SearchController.AddKeywordToSearched(Keyword.Trim());
                    }
                    string SortType = "";
                    try
                    {
                        SortType = (string)Environments.Request("st");
                    }
                    catch { }
                    if (SortType == null) SortType = "DESC";
                    if (SortType.ToLower().Equals("d")) SortType = "DESC";
                    if (SortType.ToLower().Equals("a")) SortType = "ASC";
                    string sFromDate = "";
                    try
                    {
                        sFromDate = (string)Environments.Request("sfd");
                    }
                    catch { }
                    if (sFromDate == null) sFromDate = "";
                    string sToDate = "";
                    try
                    {
                        sToDate = (string)Environments.Request("std");
                    }
                    catch { }
                    if (sToDate == null) sToDate = "";
                    string LimitedItem = "100";
                    try
                    {
                        LimitedItem = (string)Environments.Request("lm");
                    }
                    catch { }
                    if (LimitedItem == null) LimitedItem = "100";
                    string ps = "25";
                    try
                    {
                        ps = (string)Environments.Request("ps");
                    }
                    catch { }
                    if (ps == null) ps = "25";
                    Html +=
                    "<script language=javascript>" +
                    "function JumpPageSearchResult(TabModuleId,MaxItems, ItemsPerRow, NoOfVisiblePage, CurrentPage, JumpJavaScript)" +
                    "{" +
                        //"    document.getElementById(\"divProcessingSearchResult\").innerHTML = Portal.CDSP.FResultSearchWP.GetProcessingText().value;" +
                        //"    setTimeout(\"RealJumpPageSearchResult('\"+TabModuleId+\"',\"+MaxItems+\",\"+ItemsPerRow+\",\"+NoOfVisiblePage+\",\"+CurrentPage+\",'\"+JumpJavaScript+\"')\",10);" +
                     "      document.getElementById(\"divProcessingSearchResult\").innerHTML =  Portal.CDSP.FResultSearchWP.GetProcessingText().value;" +
                     "      setTimeout(\"RealJumpPageSearchResult('\"+TabModuleId+\"',\"+MaxItems+\",\"+ItemsPerRow+\",\"+NoOfVisiblePage+\",\"+CurrentPage+\",'\"+JumpJavaScript+\"')\",10);" +
                    "}" +
                    "function RealJumpPageSearchResult(TabModuleId,MaxItems, ItemsPerRow, NoOfVisiblePage, CurrentPage, JumpJavaScript)" +
                    "{" +
                    "    PageIndex = CurrentPage;" +
                    "    belongSite=document.getElementById(\"txtBelongSite\").value;" +
                    "    ShortGroupNewsItemId=document.getElementById(\"txtShortGroupNewsItem\").value;" +
                    "    sId=document.getElementById(\"txtService\").value;" +
                    "    Keyword=document.getElementById(\"txtKeyword\").value;" +
                    "    fromDate=document.getElementById(\"txtFromDate\").value;" +
                    "    toDate=document.getElementById(\"txtToDate\").value;" +
                    "    PageSize=document.getElementById(\"txtPageSize\").value;" +
                    "    LimitedItem=document.getElementById(\"txtLimitedItem\").value;" +
                    "    SortType=document.getElementById(\"txtSortType\").value;" +
                    "    retValue=Portal.CDSP.FResultSearchWP.GetHtml(belongSite,TabModuleId,sId,Keyword,ShortGroupNewsItemId,fromDate,toDate,PageSize,LimitedItem,SortType,CurrentPage,JumpJavaScript).value;" +
                    "    if(retValue.indexOf(\"ERROR\")!=-1)" +
                    "    {" +
                    "        alert(retValue);" +
                    "        return;" +
                    "    }" +
                    "    document.getElementById(\"divProcessingSearchResult\").innerHTML=\"\";" +
                    "    document.getElementById(\"divContentSearchResult\").innerHTML=retValue;" +
                    "}" +
                    "</script>" +
                    "<div id=divProcessingSearchResult></div>" +
                    "<div id=divContentSearchResult>" +
                            GetHtml(belongSite, TabModuleId, ServiceId, Keyword, ShortGroupNewsItemId, sFromDate, sToDate, ps, LimitedItem, SortType, 0, "JumpPageSearchResult") +
                    "</div>";
                    return Html;
                }
                return Html;
            }
            catch (Exception ex)
            {
                ex.Source = "";
                return Environments.GetClearFix() + GetText("SearchError", "Lỗi khi tìm kiếm! Xin tìm kiếm lại sau!");// ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string GetHtml(string belongSite, string TabModuleId, string sId, string Keyword, string ShortGroupNewsItemId, string fromDate, string toDate, string PageSize, string LimitedItem, string SortType, int CurrentPage, string JumpJavaScript)
        {
            try
            {
                TabModuleCls TabModuleCls = new TabModuleBLL().CreateModelFromXml(TabModuleId);
                if (TabModuleCls == null) throw new Exception("[" + TabModuleId + "] " + GetText("TabModuleIdNull", "not found!"));

                if (sId == null) return Environments.GetClearFix() + GetText("AccessDenied", "Truy cập không hợp lệ!");

                StringBuilder Html = new StringBuilder();
                Html.Append(
                    Environments.GetExtraStyleSheet(TabModuleCls));
                if (Keyword.Trim().Length == 0)
                {
                    Html.Append(
                        "<div class=\"clrfix\"></div>" +
                        "<div class=cssNotFoundKeywordInfo>" + GetText("1657A8D5-3458-4a12-80CE-EB4AD7DA962C", "Chưa xác định từ khóa tìm kiếm") + "</div>");
                }
                else
                {
                    SimpleSearchParamCls SimpleSearchParamCls = new SimpleSearchParamCls(Keyword);
                    SimpleSearchParamCls.ShortGroupNewsItemId = ShortGroupNewsItemId;
                    SimpleSearchParamCls.SortType = SortType;
                    SimpleSearchParamCls.SortField = "EntryDate";
                    SimpleSearchParamCls.fromDate = fromDate;
                    SimpleSearchParamCls.toDate = toDate;
                    SimpleSearchParamCls.PageSize = int.Parse(PageSize);
                    SimpleSearchParamCls.LimitedItem = int.Parse(LimitedItem);

                    SeeAlsoParamCls[] SeeAlsoParams = new SeeAlsoParamCls[0];
                    ReturnSearchParamCls[] Results = SearchController.Search(
                        TabModuleCls.belongSite,
                        sId,
                        Environments.CurrentLoginUser,
                        SimpleSearchParamCls,
                        ref SeeAlsoParams);

                    Html.Append(
                        "<input type=hidden id=txtBelongSite value=\"" + belongSite + "\">" +
                        "<input type=hidden id=txtService value=\"" + sId + "\">" +
                        "<input type=hidden id=txtKeyword value=\"" + Keyword + "\">" +
                        "<input type=hidden id=txtFromDate value=\"" + fromDate + "\">" +
                        "<input type=hidden id=txtToDate value=\"" + toDate + "\">" +
                        "<input type=hidden id=txtPageSize value=\"" + PageSize + "\">" +
                        "<input type=hidden id=txtLimitedItem value=\"" + LimitedItem + "\">" +
                        "<input type=hidden id=txtShortGroupNewsItem value=\"" + ShortGroupNewsItemId + "\">" +
                        "<input type=hidden id=txtSortType value=\"" + SortType + "\">");

                    Keyword = Portal.Environment.WebPartUtilities.CorrectForSearch(Keyword);
                    DataTable dataTable = new DataTable();

                    string ActiveLanguage = Environments.ActiveLanguage;
                    string Query = "select TOP " + LimitedItem.ToString() + " * from TableNews where belongSite='" + belongSite + "' and IsPublishing=1 and ([" + ActiveLanguage + "Body] like N'%" + Keyword + "%' or [" + ActiveLanguage + "Subject] like N'%" + Keyword + "%'  or [SearchKeyword] like N'%" + Keyword + "%')";
                    if (ShortGroupNewsItemId.Trim().Length > 0)
                    {
                        Query += " and left(fk_GroupNewsItem_Id,8)='" + ShortGroupNewsItemId + "'";
                    }
                    if (fromDate.Trim().Length > 0 && toDate.Trim().Length > 0)
                    {
                        string sfd = Portal.Environment.WebPartUtilities.VNDateToDate(fromDate).ToString("MM/dd/yyyy 00:00");
                        string std = Portal.Environment.WebPartUtilities.VNDateToDate(toDate).ToString("MM/dd/yyyy 23:59");
                        Query += " and EntryDate between '" + sfd + "' and '" + std + "'";
                    }

                    string SortField = null;
                    if (SortField == null) SortField = "";
                    if (SortField.Trim().Length > 0)
                    {
                        Query += " order by " + SortField + " " + SortType;
                    }

                    DataTable dtNews = new DataTable();
                    string PublicConnectionString = Environments.PublicConnectionString;
                    SqlDataAdapter da = new SqlDataAdapter(Query, new SqlConnection(PublicConnectionString));
                    da.Fill(dtNews);
                    int StartIndex = 0;
                    int EndIndex = 0;
                    string PagingText = new CDSPPaging().GetPaging(TabModuleId, belongSite, dtNews.Rows.Count, 10, 10, CurrentPage, JumpJavaScript, ref StartIndex, ref EndIndex);
                    string SearchKeyword = (string)Environments.Request("sKeyword");
                    while (Keyword.IndexOf("_") >= 0)
                    {
                        Keyword = Keyword.Replace("_", " ");
                    }
                    Html.Append(
                        WebPartUtilities.AttachJavascript(WebPartFolder, "FSearch.js") +
                        "<div id=\"leftsub\">" +
                            "<div class=\"leftsubHeader\">" +
                               "<h3>" + TabModuleCls.Title.ToUpper() + "</h3>" +
                                "<div class=\"clrfix\"></div>" +                                
                            "</div>" +
                            "<div class=\"textsearch\">" +
                                  GetText("KeywordSearch", "Bạn đã tìm từ") + "<b>&nbsp;" + Keyword + "</b>," +
                                  GetText("SystemHasFound", "hệ thống tìm thấy") + "&nbsp;<b><i>" + dtNews.Rows.Count.ToString("#,##0") + "</i></b>&nbsp;" +
                                  GetText("ResultMatch", "kết quả phù hợp") +
                            "</div>" +
                        "<div class=\"leftsubContent\">");
                    const int MaxValue = 40;
                    for (int iNews = StartIndex; iNews < EndIndex; iNews++)
                    {
                        string ShortContent = "";
                        try
                        {
                            ShortContent = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "ShortContent"];
                        }
                        catch { }
                        string ShortId = (string)dtNews.Rows[iNews]["ShortId"];
                        string Subject = "";
                        try
                        {
                            Subject = (string)dtNews.Rows[iNews][Environments.ActiveLanguage + "Subject"];
                        }
                        catch { }                        
                        string SmallImage = "";
                        try
                        {
                            SmallImage = (string)dtNews.Rows[iNews]["SmallImage"];
                        }
                        catch { }
                        DateTime EntryDate = (DateTime)dtNews.Rows[iNews]["EntryDate"];                        
                        // for format Shortcontent
                        int Count = 0;
                        int j = 0;
                        ShortContent = Regex.Replace(ShortContent, @"<(.|\n)*?>", string.Empty);
                        int Length = ShortContent.Length;
                        for (int i = 1; i < ShortContent.Length; i++)
                        {
                            if (ShortContent[i - 1].ToString().Equals(" ") && !ShortContent[i].ToString().Equals(" "))
                                Count++;
                            if (Count <= MaxValue)
                            {
                                j = i;
                            }
                        }
                        if (Count > MaxValue)
                        {

                            ShortContent = ShortContent.ToString().Remove(j, (Length - j));
                            ShortContent = string.Concat(ShortContent, "...");
                        }
                        string Url = Environments.GetNewsUrl(belongSite, ShortId, Subject, "_runtime");                        
                        Html.Append(
                        "<div class=\"leftsubContentwrappin\">" +
                        "<h3><a href=" + Url + ">" + Subject + "</a>" +
                        "<span class=greynews>(" + EntryDate.ToString("dd/MM/yyyy") + ")</span>" +
                        "</h3>" +
                        "<div class=\"clrfix\"></div>");
                        if (SmallImage.TrimEnd().Length >0)
                        {
                            string ImageUrl = Environments.HttpMediaRoot + "/media/" + Environments.PortalAlias + "/news/images/" + belongSite + "/" + SmallImage;
                            Html.Append("<a href=\"" + Url + "\"><img src=\"" + ImageUrl + "\" /></a>");
                        }                        
                        else
                        {                            
                            string ImageUrl = "images/no_photo.jpg";
                            Html.Append("<a href=\"" + Url + "\"><img src=\"" + ImageUrl + "\" /></a>");
                        }                        
                        Html.Append(
                                "<p>" + ShortContent + "</p>" +
                                "<div class=colfix></div>" +
                                "</div>");
                    }
                    
                    if (PagingText.Trim().Length > 0)
                    {
                        Html.Append(PagingText);
                    }
                    Html.Append(
                        "</div>"+
                        "</div>");
                }
                return Html.ToString();
            }
            catch (Exception ex)
            {
                ex.Source = "";
                return Environments.GetClearFix() + GetText("SearchError1", "Lỗi khi tìm kiếm! Xin tìm kiếm lại sau nhé!");// ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public override string ClientRenderWebPart(string BelongSite, string TabModuleId, string ViewName, string HasPorlet, LoadParamCls loadParamCls)
        {
            try
            {
                if (ViewName.Equals("default"))
                {
                    return ClientRenderWebPart(TabModuleId, HasPorlet);
                }

                return GetText("ViewNotFound", "Không tìm thấy View [" + ViewName + "]");
            }
            catch (Exception ex)
            {
                return ex.Message.ToString();
            }
        }

        public override DataTable ReadingDataService(string belongSite, string ActiveLanguage, ref string IdField, ref string SubjectField)
        {
            IdField = "Id";
            SubjectField = "Subject";
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("Id");
            dtResult.Columns.Add("Subject");
            dtResult.Rows.Add(new object[]{
                "4C60FABC-BD8F-4028-AD36-EC7AC9F49EB4","Kết quả tìm kiếm"
            });
            return dtResult;
        }


        [AjaxPro.AjaxMethod()]
        public string GetResultSearchUrl(string belongSite, string Keyword)
        {
            try
            {
                SearchController.CheckValidKeyword(Keyword);
                Keyword = Keyword.Replace(" ", "_");
                if (System.Web.HttpContext.Current.Session["AppId"] == null)
                {
                    System.Web.HttpContext.Current.Session["AppId"] = System.Guid.NewGuid().ToString();
                }
                return "ResultSearch.aspx?sKeyword=" + Keyword;

            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            return GetText("Processing", "Đang đọc dữ liệu...");
        }

        public override bool AllowFrontService
        {
            get
            {
                return true;
            }
        }

        public override void RegAjaxPro(System.Web.UI.Page ActivePage)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.CDSP.FResultSearchWP), ActivePage);
        }
    }
}
